<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-order-shipping">
    <view class="select-prod order-shipping-item">
      <view class="title">
        选择发货商品
      </view>
      <view
        v-for="(prod, index) in orderInfo.orderItems"
        :key="index"
        class="prod-item"
      >
        <view class="item">
          <view
            class="check"
            :class="{ select: queryProd(prod.orderItemId), disable: prod.prodCount < 1 || !(prod.status !== 0 && (!prod.returnMoneySts || prod.returnMoneySts < 0 || prod.returnMoneySts > 5) && ![1, 2, 5].includes(prod.platformInterventionStatus))}"
            @tap="selectProd(prod.orderItemId, prod.prodCount > 0 && (prod.status !== 0 && (!prod.returnMoneySts || prod.returnMoneySts < 0 || prod.returnMoneySts > 5)) && ![1, 2, 5].includes(prod.platformInterventionStatus))"
          />
        </view>
        <view class="img">
          <view class="prod-img-image">
            <img-show :src="prod.pic" />
          </view>
        </view>
        <view class="info">
          <view class="prod-name">
            {{ prod.prodName }}
          </view>
          <view
            v-if="prod.skuName"
            class="prod-sku"
          >
            {{ prod.skuName }}
          </view>
          <view class="shipping-num">
            <text>可发货数：{{ prod.prodCount }}，发货数量：</text>
            <view class="operation">
              <view
                class="item"
                :class="{disable:prod.changeNum === 1 }"
                @tap="handleChangeProdCount(index, -1)"
              >
                -
              </view>
              <view class="num">
                <input
                  v-model="prod.changeNum"
                  class="num-input"
                  :disabled="prod.prodCount < 1"
                  :class="{disable:prod.prodCount < 1 }"
                  type="number"
                  :max="prod.prodCount"
                  :min="1"
                  @blur="checKCount($event, index)"
                >
              </view>
              <view
                class="item"
                :class="{disable: prod.prodCount < 1 || prod.prodCount === prod.changeNum }"
                @tap="handleChangeProdCount(index, 1)"
              >
                +
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="delivery-info order-shipping-item">
      <view class="title">
        <text class="text">
          配送信息
        </text>
        <image
          v-if="orderInfo.dvyType === 1 || orderInfo.dvyType === 4"
          class="img"
          src="/static/images/editor.png"
          @tap="addrEditor"
        />
      </view>
      <view class="delivery-info-item">
        <view class="delivery-info-item-title">
          配送方式：
        </view>
        <view class="text">
          {{ orderInfo.dvyType === 1 ? '快递配送' : '同城配送' }}
        </view>
      </view>
      <view class="delivery-info-item">
        <view class="delivery-info-item-title">
          收货信息：
        </view>
        <view class="text">
          {{ userAddrOrder.receiver }} {{ userAddrOrder.mobile }}
        </view>
      </view>
      <view class="delivery-info-item">
        <view class="delivery-info-item-title">
          收货地址：
        </view>
        <view
          class="text"
        >
          {{
            `${userAddrOrder.province || ''} ${userAddrOrder.city || ''} ${userAddrOrder.area || ''} ${userAddrOrder.addr || ''}`
          }}
        </view>
      </view>
    </view>
    <view
      v-if="orderInfo.remarks"
      class="buyer-remarks order-shipping-item"
    >
      <view class="buyer-remarks-title">
        买家备注
      </view>
      <view class="buyer-remarks-content">
        {{ orderInfo.remarks }}
      </view>
    </view>
    <view class="order-shipping-item courier-info">
      <view
        class="courier-info-item"
        @tap="selecMode"
      >
        <view class="title">
          发货方式
        </view>
        <view class="text">
          {{ shippingMethods[findDeliveryMethod].name }}
        </view>
        <view class="icon" />
      </view>
      <view
        v-if="deliveryMethod === 1"
        class="courier-info-item"
      >
        <view class="title">
          配送方式
        </view>
        <view class="text">
          <radio-group @change="deliveryType=$event.detail.value/1">
            <label class="radio"><radio
              value="0"
              :checked="deliveryType == 0"
              color="#082ba6"
              style="transform:scale(0.8)"
              :disabled="isPrint!==1"
            />线上发货</label>
            &nbsp;&nbsp;
            <label
              class="radio"
            >
              <radio
                value="1"
                color="#082ba6"
                :checked="deliveryType == 1"
                style="transform:scale(0.8)"
              />线下发货
            </label>
          </radio-group>
        </view>
      </view>
      <view
        v-if="deliveryMethod === 1"
        class="courier-info-item"
        @tap="toSelecteDelivery"
      >
        <view class="title">
          物流公司
        </view>
        <view
          v-if="deliveryType===1"
          :class="['text', selectedDelivery.dvyName ? '' : 'logistics']"
        >
          {{ selectedDelivery.dvyName || '请选择物流公司' }}
        </view>
        <view
          v-if="deliveryType===0"
          :class="['text', deliveryCompanyTypeConfig?.deliveryCompanyName ? '' : 'logistics']"
        >
          {{ deliveryCompanyTypeConfig?.deliveryCompanyName || '请选择物流公司' }}
        </view>
        <view class="icon" />
      </view>
      <view
        v-if="deliveryMethod === 1 && deliveryType!==0"
        class="courier-info-item"
      >
        <view class="title">
          快递单号
        </view>
        <input
          v-model="dvyFlowId"
          type="text"
          class="input-text"
          placeholder="请输入快递单号"
        >
      </view>

      <!-- 线上发货 -->
      <template v-if="deliveryMethod === 1 && deliveryType===0 && deliveryCompanyTypeConfig.isConfig===1">
        <view
          class="courier-info-item min-height"
          @tap="onSelectShopAddr"
        >
          <view class="title">
            发货地址
          </view>
          <view :class="['text', selectShopAddr?.printAddr ? '' : 'logistics']">
            {{ selectShopAddr?.printAddr || '请选择发货地址' }}
          </view>
          <view class="icon" />
        </view>
        <view
          class="courier-info-item"
        >
          <view class="title">
            发货类型
          </view>
          <view :class="['text']">
            <radio-group @change="isPrint=$event.detail.value/1">
              <label class="radio"><radio
                label="1"
                :checked="isPrint === 1"
                color="#082ba6"
                style="transform:scale(0.8)"
              />打印面单</label>
            </radio-group>
          </view>
        </view>
        <view
          class="courier-info-item min-height"
          @tap="onSelectPrinter"
        >
          <view class="title">
            打印机
          </view>
          <view :class="['text', selerctPrinter?.printerName ? '' : 'logistics']">
            {{ selerctPrinter?.printerName || '请选择' }}
          </view>
          <view class="icon" />
        </view>
      </template>
      <!-- end 线上发货 -->
    </view>
    <view class="order-shipping-footer">
      <common-btn
        :btn-config="shippingBtnConfig"
        @handle-click-btn="handleShipping"
      />
    </view>
    <select-popup
      v-if="showSelecMode"
      :value="deliveryMethod"
      :data="shippingMethods"
      @submit-data="getDeliveryMethod"
      @cancal="cancal"
    />
    <!-- 发货地址 -->
    <select-popup
      v-if="showShopAdd && deliveryCompanyTypeConfig.shopAddrList"
      :value="selectShopAddr?.outletConfigId "
      :data="computedShopAddrList"
      @submit-data="getShopAddr"
      @cancal="showShopAdd=false"
    />
    <!-- 打印机选择 -->
    <select-popup
      v-if="showPrinter"
      :value="printerId"
      :data="computedPrinterList"
      @submit-data="getPrinter"
      @cancal="showPrinter=false"
    />
  </view>
</template>

<script setup>
import { computed, nextTick, reactive } from 'vue'

const Data = reactive({
  showSelecMode: false,
  shippingMethods: [
    {
      name: '快递配送',
      value: 1
    },
    {
      name: '无需快递',
      value: 3,
      ishidden: 1
    },
    {
      name: '同城配送',
      value: 4,
      ishidden: 1
    }
  ],
  deliveryMethod: 1,
  prodIds: [],
  orderNumber: '',
  orderId: '',
  orderInfo: {},
  userAddrOrder: {},
  // 当前选择的物流公司信息
  selectedDelivery: {},
  // 输入的运单号
  dvyFlowId: '',
  shippingBtnConfig: {
    btnText: '发货'
  }
})

const {
  showSelecMode,
  shippingMethods,
  deliveryMethod,
  orderInfo,
  userAddrOrder,
  selectedDelivery,
  dvyFlowId,
  shippingBtnConfig
} = toRefs(Data)

const findDeliveryMethod = computed(() => {
  const index = Data.shippingMethods.findIndex(
    (item) => item.value === Data.deliveryMethod
  )
  return index
})

onLoad((options) => {
  Data.orderNumber = options.orderNumber
  Data.orderId = options.orderId
  // 订单详情
  getOrderInfoById()
  nextTick(() => {
    onGetOutletConfigList()
    onGetPrinterList()
    onGetQuick100()
  })
})

onShow(() => {
  const _bbcSelectedDelivery = uni.getStorageSync('bbcSelectedDelivery')

  if (_bbcSelectedDelivery?.isOnlineDelivery) { // 线上发货地址
    deliveryCompanyTypeConfig.value = _bbcSelectedDelivery || {
      deliveryCompanyType: null,
      deliveryCompanyName: null,
      isConfig: null,
      isDefault: null,
      shopAddrList: []
    }
  } else { // 线上发货
    Data.selectedDelivery = _bbcSelectedDelivery || {}
  }
})

/**
 * 发货
 */
const handleShipping = () => {
  const endShipOrder = Data.orderInfo.orderItems.filter(x => {
    return x.prodCount > 0 && (x.status !== 0 && (!x.returnMoneySts || x.returnMoneySts < 0 || x.returnMoneySts > 5))
  })
  if (!Data.prodIds.length) {
    uni.showToast({
      title: '请选择要发货的商品！',
      icon: 'none'
    })
    return
  }
  Data.dvyFlowId = Data.dvyFlowId.trim()
  if (Data.deliveryMethod === 1 && deliveryType.value === 1 && (!Data.selectedDelivery.dvyId || !Data.dvyFlowId)) {
    uni.showToast({
      title: '请完善物流信息！',
      icon: 'none'
    })
    return
  }
  const reg = /^[a-zA-Z0-9]{4,30}$/
  if (Data.deliveryMethod === 1 && deliveryType.value === 1) {
    if (!reg.test(Data.dvyFlowId)) {
      uni.showToast({
        title: '请输入正确的快递单号！',
        icon: 'none'
      })
      return
    }
  }
  if (Data.deliveryMethod === 1 && deliveryType.value === 0) {
    if (deliveryCompanyTypeConfig.value.isConfig === 0) {
      uni.showToast({
        title: '请到商家pc端—网店配置处开通相关物流配置。',
        icon: 'none'
      })
      return
    }
    if (!selectShopAddr.value) {
      uni.showToast({
        title: '请选择发货地址',
        icon: 'none'
      })
      return
    }
    if (!selerctPrinter.value) {
      uni.showToast({
        title: '请选择打印机',
        icon: 'none'
      })
      return
    }
  }
  uni.showLoading({
    mask: true
  })

  http.request({
    url: '/order/delivery/orderItemsDelivery',
    method: 'PUT',
    hasCatch: true,
    data: {
      deliveryType: Data.deliveryMethod !== 1 ? Data.deliveryMethod : deliveryType.value,
      dvyId: Data.selectedDelivery.dvyId,
      dvyFlowId: Data.dvyFlowId ? Data.dvyFlowId : null,
      orderNumber: Data.orderNumber,
      selectOrderItems: Data.orderInfo.orderItems.filter(el => Data.prodIds.includes(el.orderItemId)),
      outletConfigId: outletConfigId.value,
      printerId: printerId.value,
      deliveryCompanyType: deliveryCompanyTypeConfig.value.deliveryCompanyType
    }
  }).then(() => {
    uni.hideLoading()
    uni.showToast({
      title: '操作成功！',
      icon: 'none',
      mask: true
    })
    setTimeout(() => {
      if (Data.prodIds.length === endShipOrder.length) {
        // #ifdef H5
        history.back()
        // #endif
        // #ifndef H5
        uni.navigateBack()
        // #endif
      } else {
        uni.removeStorageSync('bbcSelectedDelivery')
        uni.redirectTo({
          url: `/package-order/pages/order-shipping/order-shipping?orderNumber=${Data.orderInfo.orderNumber}`
        })
      }
    }, 1200)
  }).catch((e) => {
    if (e.code === 'A00001' || e.code === 'A00002') {
      const msg = (e.code === 'A00001' && e.msg?.includes('该设备编码不存在，请检查是否正确')) ? '该打印机设备编码不存在，请到商家pc端—硬件设备处检查' : e.msg
      uni.showToast({
        title: msg,
        icon: 'none',
        duration: 1500
      })
    }
  }).finally(() => {
    uni.hideLoading()
  })
}

/**
 * 修改商品数量
 * @param {Number} index 商品项索引
 * @param {Number} changeCount 变更数量
 */
const handleChangeProdCount = (index, changeCount) => {
  // 当前设置的发货数量
  const changeNum = +Data.orderInfo.orderItems[index].changeNum
  // 可发货数量
  const prodCount = Data.orderInfo.orderItems[index].prodCount
  let count = 1
  if (prodCount === 0) return

  // 增加
  if (changeCount > 0) {
    count = (changeNum + changeCount) > prodCount ? prodCount : changeNum + changeCount
  } else {
    // 减少
    count = changeNum > 1 ? changeNum - 1 : 1
  }
  Data.orderInfo.orderItems[index].changeNum = count
  resetShippingMethods()
}

const resetShippingMethods = () => {
  const tempList = Data.orderInfo.orderItems.filter(el => (el.returnMoneySts && el.returnMoneySts != 5) || !el.returnMoneySts)
  if (Data.prodIds.length !== tempList.length) {
    Data.shippingMethods[1].ishidden = 1
    Data.deliveryMethod = Data.orderInfo.dvyType !== 1 ? 4 : Data.orderInfo.dvyType
    return
  }
  let flag = 0
  for (let i = 0; i < tempList.length; i++) {
    const item = tempList[i]
    if (item.changeNum !== item.prodCount || (item.status !== 0 && item.status !== -1)) {
      flag = 1
      break
    }
  }
  Data.shippingMethods[1].ishidden = flag || undefined
  if (flag && Data.deliveryMethod === 3) {
    Data.deliveryMethod = Data.orderInfo.dvyType !== 1 ? 4 : Data.orderInfo.dvyType
  }
}

/**
 * 输入框失焦
 */
const checKCount = ($event, index) => {
  if (+$event.detail.value < 1) {
    Data.orderInfo.orderItems[index].changeNum = 1
  }
  if (+$event.detail.value > Data.orderInfo.orderItems[index].prodCount) {
    Data.orderInfo.orderItems[index].changeNum = Data.orderInfo.orderItems[index].prodCount
  }
}

/**
 * 获取订单详情
 */
const getOrderInfoById = () => {
  http.request({
    url: `/order/delivery/getOrderItemUnDelivery/${Data.orderNumber}`,
    method: 'GET'
  }).then(({ data: res }) => {
    res.orderItems.forEach(prod => {
      prod.changeNum = prod.prodCount
    })
    Data.userAddrOrder = res.userAddrOrder
    if (res.dvyType !== 1) {
      Data.deliveryMethod = 4
      changeShip()
    }
    Data.orderInfo = res
  })
}

const changeShip = () => {
  Data.shippingMethods = [{
    name: '快递配送',
    value: 1,
    ishidden: 1
  },
  {
    name: '无需快递',
    value: 3,
    ishidden: 1
  },
  {
    name: '同城配送',
    value: 4
  }]
}

// 更换地址
const addrEditor = () => {
  uni.setStorageSync('bbcUserAddrOrder', Data.orderInfo.userAddrOrder)
  uni.redirectTo({
    url: `/package-order/pages/modify-address/modify-address?orderNumber=${Data.orderNumber}&orderId=${Data.orderInfo.orderId}&shipping=1&dvyType=${Data.orderInfo.dvyType}`
  })
}

const queryProd = (orderItemId) => {
  const index = Data.prodIds.findIndex((item) => item === orderItemId)
  return index >= 0
}

/**
 * 选择要发货的商品
 * @param {Number} orderItemId 商品订单项id
 * @param {Boolean} canShipping 是否可发货
 */
const selectProd = (orderItemId, canShipping) => {
  if (!canShipping) return
  const index = Data.prodIds.findIndex((item) => item === orderItemId)
  if (index >= 0) {
    Data.prodIds.splice(index, 1)
  } else {
    Data.prodIds.push(orderItemId)
  }
  resetShippingMethods()
}

// 选择物流弹框
const selecMode = () => {
  Data.showSelecMode = true
}

const cancal = () => {
  Data.showSelecMode = false
}

const getDeliveryMethod = (value) => {
  Data.deliveryMethod = value
  Data.showSelecMode = false
  Data.selectedDelivery = {}
}

const toSelecteDelivery = () => {
  uni.navigateTo({
    url: `/package-order/pages/select-logistics/select-logistics?dvyId=${Data.selectedDelivery.dvyId}&isOnlineDelivery=${deliveryType.value}`
  })
}

const deliveryType = ref(0)// {enum} 0,1 配送方式

const outletConfigId = ref(null)
const outletConfigList = ref([])
const deliveryCompanyTypeConfig = ref({
  deliveryCompanyType: null,
  deliveryCompanyName: null,
  isConfig: null,
  isDefault: null,
  shopAddrList: []
})
// 获取网点列表
const onGetOutletConfigList = () => {
  http.request({
    url: '/shop/outletConfig/listOutletConfig',
    method: 'GET'
  }).then(({ data }) => {
    outletConfigList.value = data
    if (deliveryCompanyTypeConfig.value.deliveryCompanyType !== null) {
      data.forEach(el => {
        if (el.deliveryCompanyType === deliveryCompanyTypeConfig.value.deliveryCompanyType) {
          deliveryCompanyTypeConfig.value = el
          el.shopAddrList?.forEach(val => {
            if (val.isDefault === 1) {
              outletConfigId.value = val.outletConfigId
            }
          })
        }
      })
      return
    }
    data.forEach(el => {
      if (el.isDefault === 1) {
        // 设置选中默认配置
        deliveryCompanyTypeConfig.value = el
        el.shopAddrList.forEach(val => {
          if (val.isDefault === 1) {
            outletConfigId.value = val.outletConfigId
          }
        })
      }
    })
  })
}

const computedShopAddrList = computed(() => {
  if (deliveryCompanyTypeConfig.value.shopAddrList) {
    return deliveryCompanyTypeConfig.value.shopAddrList.map((e) => {
      return {
        name: e.printAddr,
        value: e.outletConfigId
      }
    })
  } else {
    return []
  }
})
const selectShopAddr = computed(() => {
  return deliveryCompanyTypeConfig.value?.shopAddrList?.find(el => el.outletConfigId === outletConfigId.value)
})
const showShopAdd = ref(false)
const onSelectShopAddr = () => {
  showShopAdd.value = true
}
const getShopAddr = (value) => {
  showShopAdd.value = false
  outletConfigId.value = value
}

const printerId = ref(null)
const printerList = ref([])
const selerctPrinter = computed(() => {
  return printerList.value?.find(el => el.printerId === printerId.value)
})
const computedPrinterList = computed(() => {
  return printerList.value?.map(e => ({
    name: e.printerName,
    value: e.printerId
  })) || []
})
// 获取打印机列表
const onGetPrinterList = () => {
  http.request({
    url: '/shop/printer/listPrinter',
    method: 'GET'
  }).then(({ data }) => {
    printerList.value = data
    data.forEach(el => {
      if (el.isDefault === 1) {
        // 设置选中默认配置
        printerId.value = el.printerId
      }
    })
  })
}

const showPrinter = ref(false)
//  show选择打印机
const onSelectPrinter = () => {
  if (!computedPrinterList.value.length) {
    uni.showToast({
      title: '请到商家pc端—硬件设备处配置打印机。',
      icon: 'none'
    })
    return
  }
  showPrinter.value = true
}
// 获取选择打印机id
const getPrinter = (value) => {
  showPrinter.value = false
  printerId.value = value
}

// 获取快递100配置
const isPrint = ref(0)
const onGetQuick100 = () => {
  http.request({
    url: '/sys/shopConfig/quick100',
    method: 'GET'
  }).then((res) => {
    isPrint.value = res.data ? 1 : 0
    deliveryType.value = res.data ? 0 : 1
  })
}

</script>

<style lang="scss" scoped>
@use "order-shipping";
</style>
